package com.rxt.component;

import com.rxt.config.RabbitMQConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.CorrelationDataPostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 生产者代码
 */
@Component
@Slf4j
public class DelayMessageProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;

    public void send(String message, Integer delayTime) {

        Message messagee = MessageBuilder
                .withBody(message.getBytes(StandardCharsets.UTF_8))
                        .setHeader("x-delay",delayTime)
                                .build();

        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

        // 三个参数
//        rabbitTemplate.convertAndSend(RabbitMQConfig.DELAY_EXCHANGE_NAME,
//                RabbitMQConfig.DELAY_QUEUE_ROUTING_KEY,
//                message,
//                message1 -> {
//                    message1.getMessageProperties()
//                            .setDelay(delayTime);
//                    return message1;
//                });
        rabbitTemplate.convertAndSend(RabbitMQConfig.DELAY_EXCHANGE_NAME, RabbitMQConfig.DELAY_QUEUE_ROUTING_KEY, messagee, correlationData);
        log.info("当前时间: {},  发送：: {} 到交换机", LocalDateTime.now(), message);
    }

}

